package cn.chinaflame.pagodas.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;

import cn.chinaflame.pagodas.Result.Result;
import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.entity.PaMember;
import cn.chinaflame.pagodas.entity.PaOrder;
import cn.chinaflame.pagodas.entity.PaOrderitem;
import cn.chinaflame.pagodas.entity.PaProduct;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.repository.PaMemberRepository;
import cn.chinaflame.pagodas.repository.PaOrderRepository;
import cn.chinaflame.pagodas.repository.PaOrderitemRepository;
import cn.chinaflame.pagodas.repository.PaProductRepository;
import cn.chinaflame.pagodas.req.PaydataReq;
import cn.chinaflame.pagodas.utils.DateTimes;
import cn.chinaflame.pagodas.utils.HttpPostUtil;
import cn.chinaflame.pagodas.utils.Jackson;
import cn.chinaflame.pagodas.utils.ParamPreconditions;
import cn.chinaflame.pagodas.utils.TypeRef;


/**
* @author    created by lbq
* @date	     2018年8月8日 上午10:15:19
**/
@Service
public class YwPayApiService {
	private static Logger log = LoggerFactory.getLogger(YwPayApiService.class);
	@Autowired
	private PaOrderRepository paOrderRepository;
	@Autowired
	private PaProductRepository paProductRepository;
	@Autowired
	private PaOrderitemRepository paOrderitemRepository;
	@Autowired
	private PaMemberRepository paMemberRepository;
	@Value("${pay.payment.notify_ty_url}")
	private String payNoticeUrl;
	@Value("${pay.payment.js.url}")
	private String payJsUrl;
	@Value("${pay.payment.notify.url}")
	private String payNotifyUrl;
	
	@Transactional
	public Object WxPay(PaydataReq req) throws Exception{
		//订单表
		PaOrder order=paOrderRepository.findPaOrderById(req.getOrderNo());
		ParamPreconditions.checkNotNull(order, CodeEnum.FAIL.getCode(),"没有此订单");
		//订单详情
		PaOrderitem paOrderitem=paOrderitemRepository.findOrderItemById(order.getId());
		ParamPreconditions.checkNotNull(paOrderitem, CodeEnum.FAIL.getCode(),"没有此订单详情");
		//商品表
		PaProduct product=paProductRepository.findProdictById(paOrderitem.getProductId());
		ParamPreconditions.checkNotNull(product, CodeEnum.FAIL.getCode(),"没有该商品");
		order.setPayStatus(Sysconst.PAY_STATUS_DOING);
		order.setPayTime(DateTimes.nowDateTime());
		order.setPayType("WECHAT");
		paOrderRepository.saveAndFlush(order);
//		//会员表
//		PaMember member=paMemberRepository.findByMobile(req.getAcct());
//		ParamPreconditions.checkNotNull(member, CodeEnum.FAIL.getCode(),"没有此会员");
		//实际支付金额 = 总金额减去支付金额
		BigDecimal amount = order.getTotalMoney().subtract(order.getMoney());
		//判断设定支付金额临界点是否比支付金额大
		int size = new BigDecimal("0.01").compareTo(amount);
		//支付总金额比支付临界点要小
		if (0 <= size ) {
			//传支付总金额
			req.setOrderAmount(amount.toString());
		}else {
			//否则传支付临界点金额
			req.setOrderAmount("0.01");

		}
//		req.setOrderAmount(order.getMoney().toString());


		return YsWxjsapiPay1(req);
	}
	
    /**
	 * 原生微信公众号支付
	 */
    public Object YsWxjsapiPay1(PaydataReq entity) {
		Gson gson = new Gson();
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("inputCharset", "1");//默认填 1；1 代表 UTF-8、2 代表 GBK、3 代表GB2312;
		params.put("returnUrl", ""); 	//佛龛无用
		//佛龛
		params.put("notifyUrl", payNotifyUrl);
		params.put("version", "v1.0");
		params.put("language", "1");
		params.put("orderNo", entity.getOrderNo());	//订单号		
		params.put("orderCurrency", "0");		//订单金额币种 类型	默认填 0	  
		params.put("orderDatetime", DateTimes.nowDateTime());
		params.put("issuerId", "");			//佛龛无用但必填
		params.put("sign", "");				//佛龛无用
		params.put("orderAmount", entity.getOrderAmount());
		params.put("acct", entity.getAcct());	//用户ID  ，微信为openid，支付宝为user_id
		params.put("sub_merchantId","20180201091200");
		params.put("merchantId", "1111111111111111");	//商户号
		params.put("tradeType", "PAY");
		params.put("payWay", "weixinpay");
		params.put("tradeChannel", "wechat");//可取的值：online线上；offline 线下；wechat 线上微信公众号
		params.put("tradeMethod", "wechatjs");	//可取的值：fastbank银行卡快捷; ebank网银支付;wxqrcode微信二维码;
		//aliqrcode支付宝二维码;wechatjs微信js支付，alipayjs支付宝js支付，generalpos普通pos刷卡;inteligencepos智能pos刷卡， 
//		String url = "http://tupay.china-flame.cn/gateway/trade/pay";
		log.info(gson.toJson(params));
		String receive = HttpPostUtil.doPost(payJsUrl, gson.toJson(params));		
		log.info("支付返回结果"+receive);
		if (receive == null || "".equals(receive)) {
			return Result.create("FALSE","返回接口为null");
		}
		Map<String, Map<String,String>> val = Jackson.readJson(receive, new TypeRef<Map<String, Map<String,String>>>());
		if ("0000".equals(val.get("errorCode"))) {
			return val;
		}
		return Result.create("FALSE",receive);
	}
	
}
